package com.chendx.store.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.model.common.enums.AppHttpCodeEnum;
import com.chendx.model.customer.pojo.CustomerUser;
import com.chendx.model.user.dto.RegisterDto;
import com.chendx.model.user.pojo.User;
import com.chendx.store.user.mapper.CustomerUserMapper;
import com.chendx.store.user.mapper.UserMapper;
import com.chendx.store.user.service.RegisterService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by chendx on 2022/4/27.
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private CustomerUserMapper customerUserMapper;
    @Value("${fdfs.url}")
    private String fdfsUrl;

    @Override
    public ResponseResult register(RegisterDto dto) {
        //1.校验参数
        if (dto.getUsername() == null || dto.getPassword() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        Pattern pattern = Pattern.compile("^[a-zA-Z0-9_]+$");
        if (!pattern.matcher(dto.getUsername()).matches()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (!Pattern.compile("^[^\\u4e00-\\u9fa5]+$").matcher(dto.getPassword()).matches()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer count = userMapper.selectCount(Wrappers.<User>lambdaQuery().eq(User::getPhone, dto.getPhone()));
        if (count > 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.EXIST_PHONE);
        }
        Integer nameExist = userMapper.selectCount(Wrappers.<User>lambdaQuery().eq(User::getName, dto.getUsername()));
        if (nameExist > 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.EXIST_NAME);
        }
        String salt = "123abc";
        String pwd = DigestUtils.md5Hex(dto.getPassword() + salt);

        String nickName = "";
        for (int i = 0;i< 6;i++ ){
            nickName = nickName+(char)(Math.random()*26+'a');
        }


        User apUser = new User();
        apUser.setNickName("用户_"+nickName);
        apUser.setPassword(pwd);
        apUser.setPhone(dto.getPhone());
        apUser.setUsername(dto.getUsername());
        apUser.setSalt(salt);
        apUser.setSourceType("3");
        apUser.setStatus("1");
        apUser.setHeadPic("group1/M00/00/00/inithead.jpg");
        apUser.setIsMobileCheck("1");
        apUser.setIsEmailCheck("0");
        apUser.setPoints(0);
        apUser.setExperienceValue(0);
        apUser.setUpdated(new Date());
        apUser.setCreated(new Date());
        apUser.setLastLoginIp(StringUtils.isEmpty(dto.getLastLoginIp())? null:dto.getLastLoginIp());
        try {
            int flag = userMapper.insert(apUser);
            if (flag > 0){
                addQueue(apUser);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        apUser.setSalt("");
        apUser.setPassword("");
        apUser.setHeadPic(fdfsUrl + apUser.getHeadPic());
        return ResponseResult.okResult(apUser);
    }

    @Override
    public ResponseResult existPhone(String phone) {
        if (StringUtils.isEmpty(phone)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer count = userMapper.selectCount(Wrappers.<User>lambdaQuery().eq(User::getPhone, phone));
        if (count > 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.EXIST_PHONE);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult existName(String name) {
        if (StringUtils.isEmpty(name)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer count = userMapper.selectCount(Wrappers.<User>lambdaQuery().eq(User::getUsername, name));
        if (count > 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.EXIST_PHONE);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Async("taskExecutor")
    public void addQueue(User user){
        RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbitTemplate);
        DirectExchange exchange = new DirectExchange("customer_queue_exchange");
        rabbitAdmin.declareExchange(exchange);
        Queue toQueue = new Queue(user.getUsername()+"_queue_customer");
        rabbitAdmin.declareQueue(toQueue);
        Binding binding = BindingBuilder.bind(toQueue).to(exchange).with(user.getUsername()+"_queue_customer");
        rabbitAdmin.declareBinding(binding);
        Queue fromQueue = new Queue("customer_queue_"+user.getUsername());
        rabbitAdmin.declareQueue(fromQueue);
        Binding binding2 = BindingBuilder.bind(fromQueue).to(exchange).with("customer_queue_"+user.getUsername());
        rabbitAdmin.declareBinding(binding2);

        Queue focusQueue = new Queue("sku_focus_"+user.getUsername());
        rabbitAdmin.declareQueue(focusQueue);

        Queue orderPayNoticeQueue = new Queue("order_pay_notice_"+user.getUsername());
        rabbitAdmin.declareQueue(orderPayNoticeQueue);
        DirectExchange order_pay_notice_exchange = new DirectExchange("order_pay_notice_exchange");
        rabbitAdmin.declareExchange(order_pay_notice_exchange);
        Binding binding3 = BindingBuilder.bind(orderPayNoticeQueue).to(order_pay_notice_exchange).with(user.getUsername());
        rabbitAdmin.declareBinding(binding3);

        CustomerUser customerUser = new CustomerUser();
        customerUser.setUserId(user.getId());
        customerUser.setUsername(user.getUsername());
        customerUser.setCustomerId(1);
        customerUser.setHeadpic(user.getHeadPic());
        customerUser.setCreatedTime(new Date());

        customerUserMapper.insert(customerUser);
    }

    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("^[^\\u4e00-\\u9fa5]+$");
        Matcher matcher = pattern.matcher("12呀3a....bc");
        boolean matches = matcher.matches();
        boolean b = matcher.find();
        System.out.println(matches);
    }
}
